from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 5, "max_length": 20},
            'username': {'write_only': True, 'min_length': 5, "max_length": 20},
        }

    def validate_username(self, value):
        # 检查用户名是否包含非法字符
        if not value.isalnum():
            raise serializers.ValidationError("用户名只能包含字母和数字。")
        return value

    def create(self, validated_data):
        try:
            user = User.objects.create_user(
                username=validated_data['username'],
                password=validated_data['password'],
            )
            return user
        except Exception as e:
            # 处理可能的异常，例如用户名重复
            raise serializers.ValidationError(str(e))
